package com.fancy.net.sock
{
	import com.fancy.framework.BundleManager;
	import com.fancy.framework.BundleModuleName;
	import com.fancy.framework.BundleNotice;
	import com.fancy.framework.Debug;
	import com.fancy.net.stream.DecodeBase;
	import com.fancy.net.stream.StreamDic;
	import com.fancy.ui.notice.UIKeyNotice;
	import com.fancy.ui.notice.UINoticeType;
	
	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.utils.ByteArray;

	public class SockConn extends SockBase
	{
		/** 解码锁定 */
		private var DecodeLock:Boolean = false;
		
		public function SockConn()
		{
			super();
		}
		
		override protected function connectHandler(event:Event):void
		{
			trace("SockConn::connectHandler(event:Event)");
			super.connectHandler(event);
			var notice:BundleNotice = new BundleNotice(UINoticeType.KEY_EVENT, UIKeyNotice.SOCKET_CONNECTED);
			BundleManager.instance.getLeaderByModuleName(BundleModuleName.USER_INTERFACE).execute(notice);
		}
		
		override protected function readHandler(event:ProgressEvent):void
		{
			trace("SockConn::readHandler(event:ProgressEvent)");
			super.readHandler(event);
			var cmdLen:int = SockUtil.readInt(_socket);
			var bytes:ByteArray = new ByteArray();
			_socket.readBytes(bytes, 0, cmdLen);
			_socket.readByte();//预留
			_socket.readByte();//预留
			_recvBufferArr.push(bytes);
			//var str:String = bytes.readMultiByte(bytes.bytesAvailable, "gb2312");
			//trace("剩余可读字节数", bytes.bytesAvailable);
			decodeRecvBytes();
		}
		
		override protected function closeHandler(event:Event):void
		{
			trace("SockConn::closeHandler(event:Event)");
			super.closeHandler(event);
			var notice:BundleNotice = new BundleNotice(UINoticeType.KEY_EVENT, UIKeyNotice.SOCKET_CLOSE);
			BundleManager.instance.getLeaderByModuleName(BundleModuleName.USER_INTERFACE).execute(notice);
		}
		
		private function decodeRecvBytes():void
		{
			if(DecodeLock == false)
			{
				DecodeLock = true;
				while(_recvBufferArr.length > 0)
				{
					var bytes:ByteArray = _recvBufferArr.shift();
					var mainCmdNum:int = bytes.readUnsignedByte();
					var subCmdNum:int = bytes.readUnsignedByte();
					var mainCmdStr:String = mainCmdNum < 16 ? ("0"+mainCmdNum.toString(16)) : mainCmdNum.toString(16);
					var subCmdStr:String = subCmdNum < 16 ? ("0"+subCmdNum.toString(16)) : subCmdNum.toString(16);
					var cmd:String = mainCmdStr + subCmdStr;
					var decoder:DecodeBase = StreamDic.getDecoder(cmd);
					if(decoder)
					{
						decoder.sendToModules(bytes);
					}
					else
					{
						Debug.Error("在StreamDic中，找不到消息" + cmd + "的解码器");
					}
				}
				DecodeLock = false;
			}
		}
		
	}
}